package com.wu.ssm.spring.tx;


import com.wu.ssm.spring.annotion.MyTransactional;
import com.wu.ssm.spring.aop.Proxy;
import com.wu.ssm.spring.aop.ProxyChain;
import com.wu.ssm.spring.utils.JDBCUtils;

import java.lang.reflect.Method;

/**
 * Created by wzf on 2018/12/5/005.
 */
public class ThransationProxy implements Proxy {

    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(ThransationProxy.class);

    private static final ThreadLocal<Boolean> FLAF_HODER =  ThreadLocal.withInitial(() -> false);


    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;
        boolean flag = FLAF_HODER.get();

        Method method = proxyChain.getTargetMethod();

        if(!flag && method.isAnnotationPresent(MyTransactional.class)){
            try {
                FLAF_HODER.set(true);
                JDBCUtils.beginTransaction();
                result = proxyChain.doProxyChain();
                JDBCUtils.commitThransation();
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                JDBCUtils.rollback();
            } finally {
                FLAF_HODER.remove();
            }
        }else {
            result = proxyChain.doProxyChain();
        }
        return result;
    }
}
